//
//  ViewController.m
//  YunGui
//
//  Created by wmm on 15/11/5.
//  Copyright © 2015年 hanen. All rights reserved.
//

#import "ViewController.h"
#import "MenuListViewController.h"
#import "GHRevealViewController.h"

#define LeftDistance [UIView getWidth:15.0f]
#define TextFieldHight [UIView getWidth:20.0f]

@interface ViewController ()

@property (nonatomic, strong) UITextField *userName;
@property (nonatomic, strong) UITextField *password;

@property (nonatomic, strong) UIButton *loginBtn;

//- (void)login:(id)sender;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.view.frame = CGRectMake(0.0f, 0.0f, kScreenWidth, kScreenHeight);
    self.navigationController.navigationBarHidden = YES;
    
//    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"userToken"] != nil) {
//        [self loginToHome];
//        return;
//    }
    
    [self createUI];
}

- (void)createUI{
    UIImageView *bg = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth, kScreenHeight)];
    bg.image = [UIImage imageNamed:@"Login_Bg.png"];
    [self.view addSubview:bg];
    
    UIImageView *userImg = [[UIImageView alloc] initWithFrame:CGRectMake(LeftDistance,self.view.height*0.4, TextFieldHight, TextFieldHight)];
    userImg.image = [UIImage imageNamed:@"Btn_Normal_Zhanghuhao.png"];
    
    UILabel *nameLbl = [[UILabel alloc] initWithFrame:CGRectMake(userImg.maxX+[UIView getWidth:10.0f], userImg.y, [UIView getWidth:70.0f], TextFieldHight)];
    nameLbl.text = @"员工工号";
    nameLbl.font = [ViewTool getFont:16.0];
    nameLbl.textColor = BLACKCOLOR;
    
    _userName = [[UITextField alloc] initWithFrame:CGRectMake(nameLbl.maxX+[UIView getWidth:10.0f],self.view.height*0.4-TextFieldHight/2, self.view.width-nameLbl.maxX-[UIView getWidth:10.0f]-LeftDistance,TextFieldHight*2)];
    _userName.placeholder = @"请输入工号";
    _userName.font = [ViewTool getFont:16.0];
//    _userName.keyboardType = UIKeyboardTypeNumberPad;//电话键盘
    [_userName setValue:[ViewTool getFont:16.0] forKeyPath:@"_placeholderLabel.font"];
    [_userName setValue:PLACECOLOR forKeyPath:@"_placeholderLabel.textColor"];
    _userName.delegate = self;
    
    UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(LeftDistance,_userName.maxY+[UIView getWidth:15.0f], self.view.width-LeftDistance*2, 1)];
    line.layer.borderWidth = 1;
    line.layer.borderColor = [GRAYLINECOLOR CGColor];
    
    
    UIImageView *passImg = [[UIImageView alloc] initWithFrame:CGRectMake(LeftDistance,line.maxY+[UIView getHeight:10.0f]+TextFieldHight, TextFieldHight, TextFieldHight)];
    passImg.image = [UIImage imageNamed:@"Btn_Normal_Mima.png"];

    
    UILabel *passLbl = [[UILabel alloc] initWithFrame:CGRectMake(passImg.maxX+[UIView getWidth:10.0f], passImg.y, [UIView getWidth:70.0f], TextFieldHight)];
    passLbl.text = @"登录密码";
    passLbl.font = [ViewTool getFont:16.0];
    passLbl.textColor = BLACKCOLOR;
    
    _password = [[UITextField alloc] initWithFrame:CGRectMake(passLbl.maxX+[UIView getWidth:10.0f],line.maxY+[UIView getHeight:10.0f]+TextFieldHight-TextFieldHight/2,_userName.width, TextFieldHight*2)];
    _password.placeholder = @"请输入密码";
    _password.returnKeyType =UIReturnKeyGo;//return键
    _password.secureTextEntry = YES;//密码
    _password.delegate = self;
    _password.font = [ViewTool getFont:16.0];
    [_password setValue:[ViewTool getFont:16.0] forKeyPath:@"_placeholderLabel.font"];
    [_password setValue:PLACECOLOR forKeyPath:@"_placeholderLabel.textColor"];
    
    UILabel *line2 = [[UILabel alloc] initWithFrame:CGRectMake(LeftDistance,_password.maxY+[UIView getWidth:15.0f], self.view.width-LeftDistance*2, 1)];
    line2.layer.borderWidth = 1;
    line2.layer.borderColor = [GRAYLINECOLOR CGColor];
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginBtn setBackgroundImage:[UIImage imageNamed:@"Btn_Normal_Dengdu.png"] forState:UIControlStateNormal];
    loginBtn.frame = CGRectMake(LeftDistance, line2.maxY+[UIView getHeight:60.0f], self.view.width-LeftDistance*2, [UIView getHeight:40.0f]);
    [loginBtn addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:userImg];
    [self.view addSubview:_userName];
    [self.view addSubview:line];
    [self.view addSubview:passImg];
    [self.view addSubview:_password];
    [self.view addSubview:line2];
    [self.view addSubview:loginBtn];
    [self.view addSubview:line2];
    [self.view addSubview:loginBtn];
    
    [self.view addSubview:nameLbl];
    [self.view addSubview:passLbl];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
    return YES;
}

- (void)loginToHome{
    MenuListViewController* menuVc = [[MenuListViewController alloc] init];
    if (nil==menuVc) return;
    
    menuVc.roleId = [[[NSUserDefaults standardUserDefaults] objectForKey:@"roleId"] intValue];
    
    UIColor *bgColor = [UIColor whiteColor];
    GHRevealViewController* revealController = [[GHRevealViewController alloc] initWithNibName:nil bundle:nil];
    revealController.view.backgroundColor = bgColor;
    // 绑定.
    menuVc.revealController = revealController;
    revealController.sidebarViewController = menuVc;
    // show.
    revealController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;    // 淡入淡出.
    [self presentViewController:revealController animated:YES completion:nil];
}

- (void)login{
//    _userName.text = @"heru";
//    _password.text = @"111111";
    if(_userName.text == nil | [_userName.text length] == 0 | _password.text == nil | [_password.text length] == 0)
    {
        [Tools showMessage:@"账号密码不能为空" view:self];
        return;
    }else if([_password.text length] < 4){
        [Tools showMessage:@"密码不少于4位" view:self];
        return;
    }else {
        [SVProgressHUD showWithStatus:@"登录中"];
        [_userName resignFirstResponder];
        [_password resignFirstResponder];
        //method=app.user.login&name=zhaoy&password=111111
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
        [dictionary setObject:@"app.user.login" forKey:@"method"];
        [dictionary setObject:_userName.text forKey:@"name"];
        [dictionary setObject:_password.text forKey:@"password"];
        
        [DataTool postWithUrl:HEAD_URL parameters:[DataTool addSignToDic:dictionary] success:^(id data) {
            [SVProgressHUD dismiss];
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSString *status = [(NSDictionary *)jsonDic objectForKey:@"status"];
//            NSLog(@"登录返回 %@",jsonDic);
            if ([status isEqualToString:@"SUCCESS"]) {
                NSDictionary *data = [(NSDictionary *)jsonDic objectForKey:@"data"];
                int roleId = [[(NSDictionary *)data objectForKey:@"roleId"] intValue];
                if(roleId == 1 | roleId == 2 | roleId == 4 | roleId == 27 | roleId == 29 | roleId == 30 | roleId == 31){//1管理层2城市总监4商务经理31运营专员27运营主管29运营经理30基础运营主管
                    NSString *roleName = [(NSDictionary *)data objectForKey:@"roleName"];
                    NSString *roleTag = [(NSDictionary *)data objectForKey:@"roleTag"];
                    int userId = [[(NSDictionary *)data objectForKey:@"userId"] intValue];
                    NSString *userName = [(NSDictionary *)data objectForKey:@"userName"];
                    NSString *userToken = [(NSDictionary *)data objectForKey:@"userToken"];
                    NSLog(@"%d%@%@%d%@",roleId,roleName,roleTag,userId,userName);//4商务经理business44zhaoy
                    
                    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                    [userDefaults setInteger:roleId forKey:@"roleId"];
                    [userDefaults setObject:roleName forKey:@"roleName"];
                    [userDefaults setObject:roleTag forKey:@"roleTag"];
                    [userDefaults setInteger:userId forKey:@"userId"];
                    [userDefaults setObject:userName forKey:@"userName"];
                    [userDefaults setObject:userToken forKey:@"userToken"];
                    [userDefaults synchronize];
                    
                    //创建一个消息对象
                    NSNotification * notice = [NSNotification notificationWithName:@"replaceUserToken" object:nil userInfo:@{@"replaceUserToken":@"0"}];
                    //发送消息
                    [[NSNotificationCenter defaultCenter] postNotification:notice];
                    [self loginToHome];

                }else{
                    [Tools showMessage:@"该用户不可登录APP" view:self];
                }
            }else{
                NSString *code = [(NSDictionary *)jsonDic objectForKey:@"code"];
                NSString *msg = [(NSDictionary *)jsonDic objectForKey:@"msg"];
                NSLog(@"%@%@%@",status,code,msg);
                [Tools showMessage:msg view:self];
            }
            
        } fail:^(NSError *error) {
            [SVProgressHUD dismiss];
            NSLog(@"error:%@",error);
            [Tools showMessage:@"登录失败" view:self];
        }];
    }

}

//关闭虚拟键盘。
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if(textField == _userName){
        
        [_userName resignFirstResponder];
        [_password resignFirstResponder];
    }
    if(textField == _password){
        [_userName resignFirstResponder];
        [_password resignFirstResponder];
        [self login]; 
    }
    return YES;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_userName resignFirstResponder];
    [_password resignFirstResponder];
    
}

@end
